/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.lis.device;

import com.cxhd.lis.util.Tool;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author 52461
 */
public class BC_2900_MR {

    private String baseData;
    private String base2Data;
    private String device_code = "BC-2900";
    private String code = "LA";
    private String sampletype = "全血";
    private String sampletypeId = null;

    public BC_2900_MR(String baseData, String base2data) {
        this.baseData = baseData;
        this.base2Data = base2data;
        parseComData();
//        byte[] bytes = baseData.getBytes();
//        StringBuffer bf = new StringBuffer();
//        for (byte b : bytes) {
//            System.out.println(b);
//            if (b == 4) {
//                System.out.println(b+"-----------------------");
//                bf.append("<ETO>");
//            } else if (b == 12) {
//                //System.out.println(b+"-----------------------");
//                bf.append("<FF>");
//            } else if (b == 8) {
//                //System.out.println(b+"-----------------------");
//                bf.append("<BS>");
//            } else if (b == 13) {
//                //System.out.println(b+"-----------------------");
//                bf.append("<CR>");
//            } else {
//                bf.append((char) b);
//            }
//
//        }
        System.out.println("---------------------------" + baseData + "----------------------------------");

        //  getSampleTypeId();
    }

    public void getSampleTypeId() {
        try {
            sampletypeId = Db.findFirst("select * from lis_sampletype where SAMPLEDESCRIBE='" + sampletype + "'").get("PK") + "";

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void parseComData() {
        try {
            String sampleNo = null;
            String testDate = null;
            String testTime = null;
            Map<String, String> resultMap = new HashMap<String, String>();
            String alls[] = baseData.split("&");
            System.out.println(alls[0]);
            for (int i = 0; i < alls.length; i++) {
                if (i > 0) {

                    parseResult(alls[i], resultMap);

                } else {

                    String sampleData = alls[0].split("=")[1];
                    String sampleDataParse[] = sampleData.split(",");
                    for (String sample : sampleDataParse) {
                        if (sample.contains("SampleID")) {
                            sampleNo = sample.replace("SampleID:", "");
                        } else if (sample.contains("TestTime")) {
                            testDate = sample.replace("TestTime:", "");
                        }
                    }
                }
            }
            getChart(base2Data, resultMap);
            sendDb(Tool.getSampleNo(code, sampleNo), testDate, resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("数据不完整解析错误");
        }
    }

    public void parseResult(String data, Map<String, String> map) {
        try {
            System.out.println("data=" + data);
            String das[] = data.trim().split("=");
            String key = das[0];
            String result[] = das[1].split(",");
            for (String val : result) {
                if (val.indexOf("Val") > -1) {
                    map.put(key, val.split(":")[1]);
                    System.out.println(key + ":" + val.split(":")[1]);
                }
            }
        } catch (Exception e) {
            // e.printStackTrace();
        }

    }

    public void sendDb(String sampleNo, String datetime, Map<String, String> result) {

        System.out.println(sampleNo + "  " + datetime);
        // System.out.println(result);

        for (String key : result.keySet()) {
            try {
                System.out.println("保存到数据库");
                makeInsertSqlInsert(tranMap(sampleNo, datetime, key, result.get(key)), "lis_testresult");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    }

    //转换数据结构
    public Map<String, String> tranMap(String sampleNo, String datetime, String key, String value) {
        try {
            Map<String, String> newMap = new HashMap<String, String>();

           // Record rs = Db.findFirst("select * from lis_testdescribe where TESTID='" + key.trim().replace("*", "") + "'");
              Record rs = Db.findFirst("select * from pp_device_test where TESTID='" + key.trim().replace("*", "") + "' AND DEVICEID='"+device_code+"'  limit 1");
            if (rs != null) {
              //  newMap.put("ITEMPK", rs.get("PK") + "");
                 newMap.put("ITEMPK", rs.get("TESTPK") + "");
                newMap.put("TESTID", rs.get("TESTID") + "");
                newMap.put("UNIT", rs.get("UNIT") + "");
                newMap.put("SAMPLENO", sampleNo);
                
                
                if (rs.getStr("TESTID").equalsIgnoreCase("image#WBC") || rs.getStr("TESTID").equalsIgnoreCase("image#RBC") || rs.getStr("TESTID").equalsIgnoreCase("image#PLT")) {
                    newMap.put("RESULTFLAG", "1");
                   // System.out.println("yyyyyyyyyy-----------------------");
                } else {
                    newMap.put("RESULTFLAG", "0");
                }
                newMap.put("TESTRESULT", value);
                newMap.put("MEASURETIME", datetime);
                newMap.put("DEVICEID", device_code);
                newMap.put("SAMPLETYPE", "16");
                newMap.put("UUID", Tool.string2MD5(datetime.trim() + sampleNo.trim() + device_code));
                return newMap;

            }
            return null;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    //构建sql
    private boolean makeInsertSqlInsert(Map<String, String> map, String tableName) throws Exception {

        if (map == null) {
            return false;
        }

        String sql = "";
        StringBuilder sqlHead = new StringBuilder();
        StringBuilder sqlvalue = new StringBuilder();
        int index = 0;
        String[] values = new String[map.size()];
        sqlHead.append("insert into ").append(tableName).append(" (");
        sqlvalue.append(" values (");
        for (String key : map.keySet()) {
            values[index] = map.get(key);
            index++;
            if (index == map.size()) {
                sqlHead.append("`").append(key).append("`").append(" )");
                sqlvalue.append(map.get(key) == null ? "null)" : "'" + map.get(key) + "')");
                // map.get(key)==null?"":"";
                // sqlvalue.append("? )");
            } else {
                sqlHead.append("`").append(key).append("`").append(" , ");
                sqlvalue.append(map.get(key) == null ? "null," : "'" + map.get(key) + "',");
                //sqlvalue.append("?,");
            }

        }
        sql = sqlHead.append(sqlvalue).toString();
        //System.out.println(sqlHead.append(sqlvalue).toString()+"  "+values.length);
        //logger.info(sql);
        try {
            Db.update(sql);
        } catch (Exception e) {
            System.out.println(e);
        }
        return true;

    }

    private void getChart(String baseData, Map<String, String> resultMap) {
        System.out.println(baseData.length()+"____________________________________");
        System.out.println("--------------------------------------" + baseData + "----------------------------------------------------"+baseData.length());
        String strs[] = baseData.split("87,72,105,115,116,111,68,97,116,97,22");
        String str[] = strs[1].split(",");
        String image_wbc="";
        for(int i = 0;i<str.length;i++){
         if(i<250){
           image_wbc+=str[i]+" ";
         }
        }
       // System.out.println(data);
        resultMap.put("image#WBC", image_wbc);

       
        
         String strsr[] = baseData.split("82,72,105,115,116,111,68,97,116,97,22");
         String strr[] = strsr[1].split(",");
        String image_rbc="";
        for(int i = 0;i<strr.length;i++){
         if(i<250){
           image_rbc+=strr[i]+" ";
         }
        }
       // System.out.println(data);
        resultMap.put("image#RBC", image_rbc);
        
        
         String strsp[] = baseData.split("80,72,105,115,116,111,68,97,116,97,22");
         String strp[] = strsp[1].split(",");
        String image_plt="";
        for(int i = 0;i<strp.length;i++){
         if(i<129){
           image_plt+=strp[i]+" ";
         }
        }
        
        
        resultMap.put("image#PLT", image_plt);
    }
    
    
    private void getChart2(String baseData, Map<String, String> resultMap) {

        String WBC = baseData.split("WHistoData")[1].split("RBCHisto")[0];
        byte[] wbc = WBC.getBytes();
        String image_wbc = "";
        for (byte b : wbc) {
            image_wbc += b + " ";
        }
        resultMap.put("image#WBC", image_wbc);

        String RBC = baseData.split("RHistoData")[1].split("PLTHisto")[0];
        byte[] rbc = RBC.getBytes();
        String image_rbc = "";
        for (byte b : rbc) {
            image_rbc += b + " ";
        }
        resultMap.put("image#RBC", image_rbc);
        String PLT = baseData.split("PHistoData")[1];
        byte[] plt = PLT.getBytes();
        String image_plt = "";
        for (byte b : plt) {
            image_plt += b + " ";
        }
        resultMap.put("image#PLT", image_plt);
    }

}
